package com.ruoyi.system.utils;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.http.HttpUtils;
import com.ruoyi.system.config.BailianConfig;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.charset.StandardCharsets;

/**
 * 百炼大模型工具类
 * 
 * @author ruoyi
 */
@Component
public class BailianUtils {
    private static final Logger log = LoggerFactory.getLogger(BailianUtils.class);

    private static final String API_URL = "https://dashscope.aliyuncs.com/api/v1/services/aigc/text-generation/generation";

    @Autowired
    private BailianConfig bailianConfig;

    /**
     * 发送消息到百炼大模型
     * 
     * @param message 用户消息
     * @return 模型回复
     */
    public String sendMessage(String message) {
        if (StringUtils.isEmpty(message)) {
            return "请输入您的问题";
        }

        try {
            Map<String, Object> requestBody = new HashMap<>();
            Map<String, Object> parameters = new HashMap<>();
            parameters.put("result_format", "text");
            parameters.put("temperature", 0.7);
            parameters.put("top_p", 0.8);
            
            Map<String, Object> input = new HashMap<>();
            List<Map<String, Object>> messages = new ArrayList<>();
            
            Map<String, Object> userMessage = new HashMap<>();
            userMessage.put("role", "user");
            userMessage.put("content", message);
            messages.add(userMessage);
            
            input.put("messages", messages);
            
            requestBody.put("model", bailianConfig.getModel());
            requestBody.put("input", input);
            requestBody.put("parameters", parameters);
            
            String jsonBody = JSON.toJSONString(requestBody);
            
            Map<String, String> headers = new HashMap<>();
            headers.put("Content-Type", "application/json");
            headers.put("Authorization", "Bearer " + bailianConfig.getApiKey());
            headers.put("X-DashScope-AK", bailianConfig.getAccessKeyId());
            headers.put("X-DashScope-SK", bailianConfig.getAccessKeySecret());
            
            // 使用自定义方法发送POST请求，而不是使用HttpUtils.sendPost
            String result = sendHttpPost(API_URL, headers, jsonBody);
            
            if (StringUtils.isNotEmpty(result)) {
                JSONObject jsonResult = JSON.parseObject(result);
                if (jsonResult.containsKey("output")) {
                    JSONObject output = jsonResult.getJSONObject("output");
                    if (output.containsKey("text")) {
                        return output.getString("text");
                    }
                }
                
                if (jsonResult.containsKey("message")) {
                    return "调用AI服务出错：" + jsonResult.getString("message");
                }
            }
            
            return "AI助手暂时无法回答，请稍后再试";
        } catch (Exception e) {
            log.error("调用百炼大模型API异常", e);
            return "系统异常，请稍后再试";
        }
    }
    
    /**
     * 发送HTTP POST请求
     * 
     * @param url 请求URL
     * @param headers 请求头
     * @param body 请求体
     * @return 响应内容
     */
    private String sendHttpPost(String url, Map<String, String> headers, String body) throws Exception {
        URL obj = new URL(url);
        HttpURLConnection con = (HttpURLConnection) obj.openConnection();
        
        // 设置请求方法
        con.setRequestMethod("POST");
        
        // 设置请求头
        for (Map.Entry<String, String> entry : headers.entrySet()) {
            con.setRequestProperty(entry.getKey(), entry.getValue());
        }
        
        // 设置输出
        con.setDoOutput(true);
        
        // 发送请求体
        try (OutputStreamWriter writer = new OutputStreamWriter(con.getOutputStream(), StandardCharsets.UTF_8)) {
            writer.write(body);
            writer.flush();
        }
        
        // 获取响应码
        int responseCode = con.getResponseCode();
        
        // 读取响应
        StringBuilder response = new StringBuilder();
        try (BufferedReader in = new BufferedReader(new InputStreamReader(
                responseCode >= 400 ? con.getErrorStream() : con.getInputStream(), StandardCharsets.UTF_8))) {
            String inputLine;
            while ((inputLine = in.readLine()) != null) {
                response.append(inputLine);
            }
        }
        
        return response.toString();
    }
} 